package com.silong.swing.myWindows;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 * Created by 龙哥 on 2022-01-17 17:04
 * Silong Software.
 * 将按钮添加鼠标监听器
 */

public class ButtonMouseEvent extends JFrame {

    private JButton button1;
    private JButton button2;

    //创建授权事件或委托模型的概念
    private ActionListener ac = new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("系统统一约定的AP方法 ");
        }
    };

    public ButtonMouseEvent(){
        init();
    }

    private void init(){

        button1 = new JButton("按钮一");
        button2 = new JButton("按钮二");

        Container window = this.getContentPane();
        this.setSize(800, 600);
        this.setLocationRelativeTo(null); //距中
        this.setTitle("自定义控件大小位置");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //退出窗口关闭程序

        //设置布局为空，优点:摆放灵活，缺点：代码量大，自适应能力差。
        this.setLayout(null);

        //自定义按钮的位置 ，大小
        button1.setLocation(100,50); //设置按钮位置
        button1.setSize(100,50); //设置按钮大小
        button2.setBounds(400, 50, 100, 50); //一次性设置位置与大小

        window.add(button1);
        window.add(button2);

        //添加鼠标事件
        button1.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println("button1 鼠标单击！");
            }

            @Override
            public void mousePressed(MouseEvent e) {
                System.out.println("button1 鼠标按下！");
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                System.out.println("button1 鼠标抬起！");
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                System.out.println("button1 鼠标进入按钮！");
            }

            @Override
            public void mouseExited(MouseEvent e) {
                System.out.println("button2 鼠标离开按钮！");
            }
        });

        //给特定部件添加特定的事件，比如按钮添加 ActionListener时，只触发 Clicked 事件。
        //可以为每个按钮添加多个监听器，而且从最后一个监听开始执行。
        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("按钮button2被点击了！");
            }
        });
        button2.addActionListener(ac); //添加统一监听器
        button1.addActionListener(ac); //添加统一监听器


    }

}
